package org.gesplan.listeners;

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JLabel;
import org.gesplan.util.Utils;
import org.jdesktop.beansbinding.AbstractBindingListener;
import org.jdesktop.beansbinding.Binding;
import org.jdesktop.beansbinding.Binding.SyncFailure;

/**
 * Binding listener used to log synchronization events. It displays (in given
 * label) warnings for failed synchronizations.
 *
 * @author David Erill
 */
public class LoggingBindingListener extends AbstractBindingListener {

    private JLabel outputLabel;
    private JButton saveButton = null;


    public LoggingBindingListener(JButton saveButton) {
        this.saveButton = saveButton;
    }


    @SuppressWarnings("rawtypes")
	@Override
    public void syncFailed(Binding binding, SyncFailure fail) {
        String description;
        if ((fail != null) && (fail.getType() == Binding.SyncFailureType.VALIDATION_FAILED)) {
            description = fail.getValidationResult().getDescription();
        } else {
            description = "Sync failed!";
        }
        String msg = "[" + binding.getName() + "] " + description;
        if (outputLabel == null) {
            outputLabel = Utils.getValidationLabel();
        }        
        if (outputLabel != null) {            
            outputLabel.setText(msg);            
            outputLabel.setForeground(Color.red);            
        }        
        saveButton.setEnabled(false);
    }


    @SuppressWarnings("rawtypes")
	@Override
    public void synced(Binding binding) {
        String msg = "[" + binding.getName() + "] Synced";
        if (outputLabel == null) {
            outputLabel = Utils.getValidationLabel();
        }        
        if (outputLabel != null) {            
            outputLabel.setText(msg);
            outputLabel.setForeground(Color.black);             
            saveButton.setEnabled(true);
        }
    }
    
    
}